// storedata.js

// Gaurav Dubey

// CSCI 5471 project

// Fall 2007


// This function sends data to the server. It does the following stuffs:
// 1. Encrypt the text using Blowfish with a randomly generated key. (The commas will go eventually...)
// 2. Encrypt the key using RSA and a user-supplied public key.
// 3. Post the encrypted text, encrypted key, and post title to storedata.php on the server.

function encrypt(e, n)
{
	//First, generate a random Blowfish key, using the jsbn library's random number generator.
	var sr = new SecureRandom();
	var keyBytes = new Array(10);
	sr.nextBytes(keyBytes);
	var bfKey = bytesToString(keyBytes);

	//Document title:
	var title = document.getElementById("title").value;
	var form = document.getElementById("adddata");

	//Retrieve the javascript element containing the post, and get the plaintext:
	var dataField = document.getElementById("data");
	var plaintext = dataField.value;

	//Next: encrypt the plaintext using the Blowfish key.
	var bf = new Blowfish(bfKey);
	var ciphertext = bf.encrypt(plaintext);	//For now, we're using a simplistic Blowfish encryption library: we'll find a more advanced one supporting CBC later.

	//Using XMLHttpRequest, retrieve a list of public key 'n's by sending off the 'users' array.
	var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
	request.open("POST", "userkeys.php", false);
	request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	var userArray = form["users[]"];
	var users = new Array();
	var userString = "";
	var usersIndex = 0;
	for(var i = 0; i < userArray.length; i++)
	{
		if(userArray[i].checked)
		{
			users[usersIndex] = userArray[i].value;
			userString = userString + users[usersIndex];
			usersIndex++;
			if(i < userArray.length - 1)
			{
				userString += ",";
			}
		}
	}
	
	// Add username to users (array) and userString
	var username = document.getElementById("username").value;
	
	userString = userString + "," + username;
	//alert(userString);
	
	users.push(username);
	
	
	request.send("users=" + userString);
	if (request.readyState == 4 && request.status == 200)
	{
		if (request.responseText)
		{
			//DEBUG
			//alert(request.responseText);
			//Here, split the response text into an array of 'n' values.
			var nvalues = request.responseText.split('\n');
			
			//DEBUG
			//alert("users: " + users.length + "\nnvalues: " + nvalues.length);

			//Next: encrypt the Blowfish key using each of these keys and send it to the server.
			for(var i = 0; i < users.length; i++)
			{
				//DEBUG
				//alert(nvalues[i]);
				
				request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
				request.open("POST", "storekey.php")
				request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				var rsaKey = new RSAKey();
				rsaKey.setPublic(nvalues[i], e);
				var encryptedBFKey = rsaKey.encrypt(bfKey);
				var response = "title=" + title + "&user=" + users[i] + "&bfkey=" + encryptedBFKey;
				request.send(response);
			}
		}
		else
		{
			alert("Error retrieving public keys: no response text.");
		}
	}
	else
	{
		alert("Error retrieving public keys: request failed.");
	}
	
	//Next: rewrite the text area containing the post with the Blowfish-encrypted ciphertext.
	dataField.value = ciphertext;
	
	//Finally: post everything to the remote file.
	
	//DEBUG: display all stuffs here
	//alert("BF key: " + bfKey + "\nData: " + plaintext + "\nBF-encrypted data: " + ciphertext);
	
	form.submit();
}


// This function generates the 'e' and 'n' values used for encryption. Note that initially, these will have to be entered as part of the form.
// At the end, this function calls encrypt(), which sends the data along to the php page.

function retrievePublicKey()
{
	//For the time being, just slurp e and n from their respective form fields. (Yeah, I know it's ugly. And not just the word 'slurp' either.)
	var eField = document.getElementById("e");
	var nField = document.getElementById("n");
	
	var e = eField.value;
	var n = nField.value;
	n = n.replace(/\n/, "");
	e = e.replace(/\n/, "");
	
	//Check these fields, just to be sure.
	if(n != null && e != null && n.length > 0 && e.length > 0)
	{
		//This function will take care of retrieving the post data.
		encrypt(e, n);
	}
	else
	{
		alert("There's something wrong with your public key.\nAnd that's terrible.");
	}
}


//This function does not work optimally right now. It is necessary to rewrite the code to make a consistent 

function bytesToString(byteArray)
{
	var output = "";
	for(var i = 0; i < byteArray.length; i++)
	{
		output += byteArray[i].toString(16);	//Let's hope this works.
	}
	return output.substring(0,27);
}